package cn.edu.swu.miniwebsvr.handler;

import cn.edu.swu.miniwebsvr.core.Handler;
import cn.edu.swu.miniwebsvr.core.Parameter;

import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Map;

public class EchoHandler implements Handler {
    @Override
    public void handle(Parameter request, OutputStream response) {
        PrintWriter writer = new PrintWriter(response);
        Map<String ,String> params = request.getAllParams();

        StringBuilder contentBuilder = new StringBuilder();
        contentBuilder.append("<!DOCTYPE html>\n");
        contentBuilder.append("<html lang=\"zh-CN\">\n");
        contentBuilder.append("<body>\n");
        contentBuilder.append("<h1>Echo Server Response</h1>\n");
        contentBuilder.append("<h2>Request Details:</h2>\n");
        contentBuilder.append("<p>Method: ")
                .append(request.getMethod())
                .append("</p>");

        // [222024321072041/王耀东] 根据接收到的参数Map构建HTML列表，回显给客户端
        if (params.isEmpty()) {
            contentBuilder.append("<h2>No Parameters Received.</h2>");
        } else {
            contentBuilder.append("<h2>Received Parameters:</h2>");
            contentBuilder.append("<ul>");
            for (Map.Entry<String,String> entry : params.entrySet()) {
                contentBuilder.append("<li><strong>").append(entry.getKey())
                            .append("</strong>:").append(entry.getValue())
                            .append("</li>");
            }
            contentBuilder.append("</ul>");
        }
        contentBuilder.append("</body>\n");
        contentBuilder.append("</html>");

        String content = contentBuilder.toString();

        // [222024321072041/王耀东] 构造完整的 HTTP 响应头
        writer.println("HTTP/1.1 200 OK");
        writer.println("Content-Type: text/html; charset=UTF-8");
        writer.println("Content-Length: " + content.getBytes().length);
        writer.println("Connection: close");
        writer.println("Server: MiniWebSvr/1.0");
        writer.println("Cache-Control: no-cache, no-store, must-revalidate");
        writer.println("Pragma: no-cache");
        writer.println("Expires: 0");
        writer.println(); // 空行分隔头部和正文

        writer.println(content);

    }
}
